package com.offcn.service.impl;

import com.offcn.entity.Product;
import com.offcn.entity.Trolley;
import com.offcn.mapper.CardMapper;
import com.offcn.mapper.ProductMapper;
import com.offcn.service.CardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("cardService")
public class CardServiceImpl implements CardService {
    @Resource
    private CardMapper cardMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public int addTrolley(int id, int uid) {
        int num = -1;
        /**
         * 判断当前这个商品在购物车中是否存在
         * 1、没有订单号的商品
         * 2、当前商品id
         * 3、当前用户
         */
        // Trolley t = trolleyDao.findTrolleyIsexist(trolley);
        Trolley t = cardMapper.selectByUidAndId(id,uid);
        //处理一个简单的业务(提供数量)
        if (null == t) {
            cardMapper.intoTroller(uid, id, 1, "" + System.currentTimeMillis());
            num = 1;
        } else {
            num = t.getNumber() + 1;
            cardMapper.updateTroller(uid, num,id);
        }
        return num;
    }

    @Override
    public int reduceTrolley(int id, int uid) {
        int num = -1;
        Trolley t = cardMapper.selectByUidAndId(id,uid);
        if(t.getNumber()>=2){
            num=t.getNumber() -1;
            cardMapper.updateTroller(uid, num,id);
        }
        return num;
    }


    @Override
    public List<Trolley> selectByUid(int uid) {
        List<Trolley> trolleys = cardMapper.selectAll(uid);

        for (int i = 0; i < trolleys.size(); i++) {
            trolleys.get(i).setImage(productMapper.selectById(trolleys.get(i).getId()).getImage());
            trolleys.get(i).setName(productMapper.selectById(trolleys.get(i).getId()).getName());
            trolleys.get(i).setPrice(productMapper.selectById(trolleys.get(i).getId()).getPrice());
        }
        return trolleys;
    }


    @Override
    public List<Product> selectAll(Integer id) {
        List<Trolley> trolleys =     cardMapper.selectAll(id);
        List<Integer> li  = new ArrayList<Integer>();
        for(int i=0;i<trolleys.size();i++){
            li.add(trolleys.get(i).getId());
        }
        List<Product> productList =  productMapper.selectAllById(li.toArray());
        System.out.println(productList.get(0).getName()+"\t"+productList.get(0).getPrice());
        return productList;
    }

    @Override
    public int deleteByUidAndId(int id, int uid) {
        return cardMapper.deleteT(id,uid);
    }


}
